package com.gzyj.web.service;

import com.gzyj.web.config.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/ws/gps/{vehId}")
@Component
public class WebSocketService {
    private static final Logger log = LoggerFactory.getLogger(WebSocketService.class);


    private static ConcurrentHashMap<String, WebSocketClient> webSocketMap = new ConcurrentHashMap<>();


    /**
     * 客户端与服务端连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("vehId") String vehId, Session session) {

        WebSocketClient client = new WebSocketClient();
        client.setSession(session);
        client.setUri(session.getRequestURI().toString());
        webSocketMap.put(vehId, client);
        log.info("连接成功！" + session.getRequestURI().toString());
        log.info("连接成功！" + session);
    }

    /**
     * 客户端与服务端连接关闭
     */
    @OnClose
    public void onClose() {
        log.info("连接关闭！");
    }

    /**
     * 客户端与服务端连接异常
     *
     * @param error
     * @param session
     */
    @OnError
    public void onError(Throwable error, Session session) {
    }

    /**
     * 客户端向服务端发送消息
     *
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMsg(Session session, String message) throws IOException {
        log.info("消息测试！");
    }


    /**
     * 向指定客户端发送消息
     *
     * @param message
     */
    public void sendMessage(String vehId, String message) {
        try {
            log.info("准备发消息！" + vehId);
            WebSocketClient webSocketClient = webSocketMap.get(vehId);
            log.info("连接成功》》》》》》》》》" + webSocketMap);
            if (webSocketClient != null) {
                log.info("发送的消息是！" + message);
                webSocketClient.getSession().getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.info("失败");
            throw new RuntimeException(e.getMessage());
        }
    }

    public void sendMessage(String message) {
        try {
            Iterator<Map.Entry<String, WebSocketClient>> entries = webSocketMap.entrySet().iterator();

            while (entries.hasNext()) {

                Map.Entry<String, WebSocketClient> entry = entries.next();
                WebSocketClient webSocketClient = entry.getValue();
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                if (webSocketClient != null) {
                    log.info("发送的消息是！" + message);
                    webSocketClient.getSession().getBasicRemote().sendText(message);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.info("失败");
            throw new RuntimeException(e.getMessage());
        }
    }
}
